package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.IntellectualProperty;
import com.gxuwz.stats.service.IntellectualPropertyService;
import com.gxuwz.stats.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/intellectualProperty")
public class IntellectualPropertyController {

    private final IntellectualPropertyService intellectualPropertyService;
    private final UserService userService;

    public IntellectualPropertyController(
            IntellectualPropertyService intellectualPropertyService,
            UserService userService) {
        this.intellectualPropertyService = intellectualPropertyService;
        this.userService = userService;
    }

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getPropertyList(
            @RequestParam(required = false) String nameKeyword,
            @RequestParam(required = false) String numberKeyword,
            @RequestParam(required = false) String intellectualCategory,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            Page<IntellectualProperty> page = new Page<>(currentPage, pageSize);
            QueryWrapper<IntellectualProperty> queryWrapper = new QueryWrapper<>();

            if (nameKeyword != null && !nameKeyword.isEmpty()) {
                queryWrapper.like("intellectual_achievement_name", nameKeyword);
            }
            if (numberKeyword != null && !numberKeyword.isEmpty()) {
                queryWrapper.like("authorization_number", numberKeyword);
            }
            if (intellectualCategory != null && !intellectualCategory.isEmpty()) {
                queryWrapper.eq("intellectual_category", intellectualCategory);
            }

            IPage<IntellectualProperty> resultPage = intellectualPropertyService.getIntellectualPropertyList(page, queryWrapper);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PostMapping("/add")
    public ResponseEntity<?> saveProperty(@RequestBody IntellectualProperty intellectualProperty) {
        String username = intellectualProperty.getUsername();
        if (username == null || username.isEmpty()) {
            return ResponseEntity.badRequest().body("用户名不能为空");
        }

        Integer userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            return ResponseEntity.badRequest().body("用户不存在");
        }

        intellectualProperty.setUserId(userId);
        intellectualProperty.setIntellectualId(null);
        boolean isSaved = intellectualPropertyService.save(intellectualProperty);

        return isSaved ?
                ResponseEntity.status(HttpStatus.CREATED).build() :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    @PutMapping("/update/{id}")
    public ResponseEntity<?> updateProperty(
            @PathVariable("id") Long id,
            @RequestBody IntellectualProperty intellectualProperty) {
        try {
            String username = intellectualProperty.getUsername();
            if (username == null || username.isEmpty()) {
                return ResponseEntity.badRequest().body("用户名不能为空");
            }

            Integer userId = userService.getUserIdByUsername(username);
            if (userId == null) {
                return ResponseEntity.badRequest().body("用户不存在");
            }

            intellectualProperty.setIntellectualId(id);
            intellectualProperty.setUserId(userId);
            boolean isUpdated = intellectualPropertyService.updateById(intellectualProperty);

            return isUpdated ?
                    ResponseEntity.ok().build() :
                    ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    public ResponseEntity<Void> deleteProperty(@RequestBody List<Long> ids) {
        boolean success = intellectualPropertyService.removeByIds(ids);
        return success ?
                ResponseEntity.noContent().build() :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}
